////
////  CDNetWorkService.swift
////  CandyDate
////
////  Created by zolobdz on 2017/9/27.
////  Copyright © 2017年 HeChao. All rights reserved.
////
//
//import Foundation
//import Moya
//import Alamofire
//import Result
//import ObjectMapper
//import Result
//
//private let CDNetWorkProvider = MoyaProvider<<#Target: TargetType#>>(requestClosure: requestTimeoutClosure, plugins: [networkPlugin,RequestLoadingPlugin()])
//
//typealias SuccessClosure = (_ result: AnyObject?,_ code: Int,_ msg: String) -> Void
//typealias FailClosure = (_ errorMsg: String) -> Void
//
//let CDNetworkEnvironment = ["dev" : (baseURL: "https://t.api.datasheetdownload.cn/",name: "开发环境"),
//                            "ad hoc" : (baseURL: "https://gray.api.datasheetdownload.cn",name: "测试环境"),
//                            "distribute" : (baseURL: "https://api.datasheetdownload.cn/",name: "正式环境")]
//
//class CDNetWorkService {
//
//    static let shared = CDNetWorkService()
//    private init() {
//        #if APPSTORE
//            currentEnvironment = CDNetworkEnvironment["distribute"]!
//            return
//        #else
//
//            if let name = UserDefaults.standard.object(forKey: CDUserDefaultKey.networkEnvironmentNameKey) as? String,!name.isEmpty
//            {
//                if let environment = CDNetworkEnvironment[name]
//                {
//                    currentEnvironment = environment
//                    return
//                }
//            }
//            #if DEBUG
//                // 开发环境
//                currentEnvironment = CDNetworkEnvironment["dev"]!
//            #else
//                // ad hoc 测试环境
//                currentEnvironment = CDNetworkEnvironment["ad hoc"]!
//            #endif
//        #endif
//
//    }
//
//    var netConditionStatus = NetworkReachabilityManager.NetworkReachabilityStatus.notReachable
//
//    var currentEnvironment : (baseURL: String,name: String)
//
//    //监听网络状态
//    func  listenNetwork(){
//        let manager = NetworkReachabilityManager(host: "www.baidu.com")
//        manager?.listener = { status in
//            self.netConditionStatus = status
//            switch status {
//            case .unknown,.notReachable:
//                break
//            case .reachable:
//
//                break
//
//            }
////            print("Network Status Changed: \(status)")
//        }
//        manager?.startListening()
//    }
//
//    // 请求返回的数据是一个数组
//    class func requestArrayWithTarget<T: Mappable>(target: CDRequestAPI, elemtType: T.Type, successClosure: @escaping SuccessClosure, failClosure: @escaping FailClosure) {
//        CDNetWorkProvider.request(target) { result in
//            switch result{
//            case let .success(response):
//                if let temp = try? response.mapJSON()
//                {
//                    if let dict = temp as? Dictionary<String,Any>{
//
//                        var model = [T]() as AnyObject
//                        if let data = dict["data"] as? [[String : Any]],!data.isEmpty
//                        {
//                            model = Mapper<T>().mapArray(JSONArray: data) as AnyObject
//                        }
//                        CDUtility.log("\(target.path)\n\(dict)")
//
//                        let rc = Int((dict["rc"] as? String ?? "11"))!
//                        let msg = dict["msg"] as? String  ?? "亲，发生了未知错误"
//                        handleAllResponseCode(rc)
//                        successClosure(model, rc , msg)
//                    }
//                }
//            case let .failure(error):
//                let nError = error as NSError
//                let message = handleResponseFailure(nError)
//                failClosure(message)
//            }
//        }
//    }
//
//    // 请求返回的数据是一个模型
//    class func requestDataWithTarget<T: Mappable>(target: CDRequestAPI, type: T.Type, successClosure: @escaping SuccessClosure, failClosure: @escaping FailClosure) {
//        CDNetWorkProvider.request(target) { result in
//            switch result{
//            case let .success(response):
//                if let temp = try? response.mapJSON()
//                {
//                    if let dict = temp as? Dictionary<String,Any>{
//
//                        var model: AnyObject
//                        model = T(JSON: [:]) as AnyObject
//                        if let data = dict["data"] as? Dictionary<String,Any>,!data.isEmpty // 直接解析data层，这样model里面的map映射就都不需要写 data.xxx
//                        {
//                            model = T(JSON: data) as AnyObject
//                        }
//                        if let data = dict["data"] as? [[String : Any]],!data.isEmpty
//                        {
//                            model = Mapper<T>().mapArray(JSONArray: data) as AnyObject
////                            CDUtility.log(model)
////                            CDUtility.log(dict.count)
//                        }
//                        CDUtility.log("\(target.path)\n\(dict)")
//
//                        let rc = Int((dict["rc"] as? String ?? "11"))!
//                        let msg = dict["msg"] as? String  ?? "亲，发生了未知错误"
//                        handleAllResponseCode(rc)
//                        successClosure(model, rc , msg)
//                    }
//                }
//            case let .failure(error):
//                let nError = error as NSError
//                let message = handleResponseFailure(nError)
//                failClosure(message)
//            }
//        }
//    }
//
//
//    // 请求返回的数据不重要(返回BaseResponse对象，有Dictionary类型的data属性)，不参与控制器的dataSource
//    class func requestDataWithTarget(target: CDRequestAPI, successClosure: @escaping SuccessClosure, failClosure: @escaping FailClosure) {
//        CDNetWorkProvider.request(target) { result in
//            switch result{
//            case let .success(response):
//                if let temp = try? response.mapJSON()
//                {
//                    if let dict = temp as? Dictionary<String,Any>{
//                        let model = BaseResponse(JSON: dict)
//                        let rc = Int((dict["rc"] as? String ?? "\(CDNetworkExceptionNeedLogin)"))!
//                        let msg = dict["msg"] as? String ?? "亲，发生了未知错误"
//                        CDUtility.log("\(target.path)\n\(dict)")
//                        handleAllResponseCode(rc)
//                        successClosure(model as AnyObject, rc, msg)
//                    }
//
//                }
//            case let .failure(error):
//                let nError = error as NSError
//                let message = handleResponseFailure(nError)
//                failClosure(message)
//            }
//        }
//    }
//
//    //MARK: Private
//
//    // 处理请求成功后的异常code
//    class func handleAllResponseCode(_ code: Int) {
//        if code == CDNetworkExceptionNeedLogin
//        {
//            MyselfSingleton.shared.logOutcClean()
//            UIManager.shared.tabBarController.showLoginViewController()
//            NotificationCenter.default.post(name: NSNotification.Name.CDContactNeedLogoutNotificationKey, object: nil)
//        }
//    }
//
//    class func handleResponseFailure(_ error: NSError) -> String{
//        var message = error.localizedDescription
//        if error.localizedDescription.contains("offline")
//        {
//            message = "网络连接断开"
//        }
//        return message
//    }
//
//    // 取消所有GET请求
//    class func cancelAll(_ completionHandle: @escaping ()->Void ) {
//        CDUtility.log(CDNetWorkProvider.manager.session)
//        //        CDNetWorkProvider.manager.session.invalidateAndCancel()
//        //        completionHandle()
//        CDNetWorkProvider.manager.session.getAllTasks { (tasks) in
//            for task in tasks
//            {
//                if let httpMethod = task.originalRequest?.httpMethod
//                {
//                    if httpMethod.lowercased() == "get"
//                    {
//                        CDUtility.log("Request Cancaled:" + (task.originalRequest?.url?.absoluteString ?? ""))
//                        task.cancel()
//                    }
//                }
//            }
//            DispatchQueue.main.async {
//                completionHandle()
//            }
//        }
//
//    }
//
//}
//
//
